package com.fuhao.pay.callback.template.CallbackTemplate;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.fuhao.alipay.config.AlipayConfig;
import com.fuhao.pay.callback.template.AbstractPayCallbackTemplate;
import com.fuhao.pay.constant.PayConstant;
import com.fuhao.pay.entity.PaymentTransactionEntity;
import com.fuhao.pay.mapper.PaymentTransactionMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author zhang
 * @title: 支付宝回调模板
 */
@Component
@Slf4j
public class AliPayCallbackTemplate extends AbstractPayCallbackTemplate {
    @Autowired
    private PaymentTransactionMapper paymentTransactionMapper;

    @Override
    public Map<String, String> verifySignature(HttpServletRequest req, HttpServletResponse resp,Map<String, String> params) {
        //日志记录,一般需要把日志记录到数据库中
        log.info("######支付宝异步通知开始######，params：{}"+params);
        //验签
        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        log.info("######支付宝异步验签######，signVerified："+signVerified);
        //——请在这里编写您的程序（以下代码仅作参考）——
        if(!signVerified) {
            log.info("支付宝验证签名结果[失败].");
            params.put(PayConstant.RESULT_NAME, PayConstant.RESULT_PAYCODE_201);
        }else {
            log.info("支付宝验证签名结果[成功].");
            String orderNumber = params.get("out_trade_no");
            params.put("paymentId", orderNumber);
            params.put(PayConstant.RESULT_NAME, PayConstant.RESULT_PAYCODE_200);
        }
        return params;
    }

    @Override
    public String asyncService(Map<String, String> verifySignature) {
        String status = verifySignature.get("trade_status");
        if(!(status.equals("TRADE_SUCCESS") || status.equals("TRADE_FINISHED"))){
            return failResult();
        }
        String orderId = verifySignature.get("out_trade_no");//唯一支付id，注意不是第三方支付id，也不是订单id
        //判断订单是否已支付状态，解决幂等性
        PaymentTransactionEntity paymentTransaction = paymentTransactionMapper.selectByPaymentId(orderId);
        if (paymentTransaction.getPaymentStatus() == PayConstant.PAY_STATUS_SUCCESS) {
            // 网络重试中，之前已经支付过
            return successResult();
        }
        // 2.将状态改为已经支付成功
        paymentTransactionMapper.updatePaymentStatus(PayConstant.PAY_STATUS_SUCCESS, orderId,PayConstant.ALI_CHANNEL);
        // 3.调用积分服务接口增加积分(处理幂等性问题)

        return successResult();
    }

    @Override
    public String failResult() {
        return PayConstant.ALI_RESULT_FAIL;
    }

    @Override
    public String successResult() {
        return PayConstant.ALI_RESULT_SUCCESS;
    }
}
